using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows.Input;
using System.Windows;
using System.Windows.Media;
using WPF_MVVM_Test.MVVM_Model.Process;
using WPF_MVVM_Test.MVVM_ViewModel;
using WPF_MVVM_Test.MVVM_Services;

namespace WPF_MVVM_Test.MVVM_ViewModel.ProductionOrder
{
    public class AddTaskDialogViewModel : INotifyPropertyChanged
    {
        private readonly ProcessService _processService;
        private readonly string _productionOrderId;
        private readonly string _processStepId;
        private readonly string _processRouteId;
        private readonly string _processRouteName;
        private readonly decimal _planQuantity;
        private readonly DateTime _planStartTime;
        private readonly DateTime _planEndTime;

        // 添加可变的字段来存储当前值
        private decimal _currentPlanQuantity;
        private DateTime _currentPlanStartTime;
        private DateTime _currentPlanEndTime;

        public AddTaskDialogViewModel(string productionOrderId, string processStepId, string processRouteId, string processRouteName, decimal planQuantity, DateTime planStartTime, DateTime planEndTime)
        {
            _productionOrderId = productionOrderId;
            _processStepId = processStepId;
            _processRouteId = processRouteId;
            _processRouteName = processRouteName;
            _planQuantity = planQuantity;
            _planStartTime = planStartTime;
            _planEndTime = planEndTime;
            
            // 初始化可变字段
            _currentPlanQuantity = planQuantity;
            _currentPlanStartTime = planStartTime;
            _currentPlanEndTime = planEndTime;
            
            _processService = new ProcessService();

            // 初始化默认值
            InitializeDefaultValues();
            
            // 初始化命令
            InitializeCommands();
            
            // 加载站点数据
            LoadStationNames();
        }

        #region 属性
        private string _taskNumber = string.Empty;
        public string TaskNumber
        {
            get => _taskNumber;
            set
            {
                _taskNumber = value;
                OnPropertyChanged();
            }
        }

        private string _taskName = string.Empty;
        public string TaskName
        {
            get => _taskName;
            set
            {
                _taskName = value;
                OnPropertyChanged();
            }
        }

        private string _stationId = string.Empty;
        public string StationId
        {
            get => _stationId;
            set
            {
                _stationId = value;
                OnPropertyChanged();
            }
        }

        private string _taskColor = "#1890FF";
        public string TaskColor
        {
            get => _taskColor;
            set
            {
                _taskColor = value;
                OnPropertyChanged();
            }
        }

        public decimal PlanQuantity
        {
            get => _currentPlanQuantity;
            set
            {
                _currentPlanQuantity = value;
                OnPropertyChanged();
            }
        }

        public DateTime PlanStartTime
        {
            get => _currentPlanStartTime;
            set
            {
                _currentPlanStartTime = value;
                OnPropertyChanged();
            }
        }

        public DateTime PlanEndTime
        {
            get => _currentPlanEndTime;
            set
            {
                _currentPlanEndTime = value;
                OnPropertyChanged();
            }
        }

        private bool _isSystemNumber = true;
        public bool IsSystemNumber
        {
            get => _isSystemNumber;
            set
            {
                _isSystemNumber = value;
                OnPropertyChanged();
                OnPropertyChanged(nameof(IsSystemNumberEnabled));
                
                if (value)
                {
                    // 生成系统编号
                    GenerateSystemTaskNumber();
                }
            }
        }

        public bool IsSystemNumberEnabled => !IsSystemNumber;

        private string _remarks = string.Empty;
        public string Remarks
        {
            get => _remarks;
            set
            {
                _remarks = value;
                OnPropertyChanged();
            }
        }

        // 站点相关
        public ObservableCollection<StationModel> StationNames { get; set; } = new ObservableCollection<StationModel>();
        
        private StationModel? _selectedStationName;
        public StationModel? SelectedStationName
        {
            get => _selectedStationName;
            set
            {
                _selectedStationName = value;
                OnPropertyChanged();
                
                if (value != null)
                {
                    StationId = value.Id;
                }
            }
        }

        // 对话框结果
        private bool _dialogResult;
        public bool DialogResult
        {
            get => _dialogResult;
            set
            {
                _dialogResult = value;
                OnPropertyChanged();
            }
        }

        // 添加公共属性来访问私有字段
        public string ProcessStepId => _processStepId;
        public string ProcessRouteId => _processRouteId;
        public string ProcessRouteName => _processRouteName;
        public string ProductionOrderId => _productionOrderId;
        #endregion

        #region 命令
        public ICommand ConfirmCommand { get; private set; } = null!;
        public ICommand CancelCommand { get; private set; } = null!;
        public ICommand CloseCommand { get; private set; } = null!;
        public ICommand PickColorCommand { get; private set; } = null!;

        private void InitializeCommands()
        {
            ConfirmCommand = new RelayCommand(Confirm);
            CancelCommand = new RelayCommand(Cancel);
            CloseCommand = new RelayCommand(Close);
            PickColorCommand = new RelayCommand(PickColor);
        }

        private void Confirm()
        {
            if (ValidateInput())
            {
                DialogResult = true;
                Close();
            }
        }

        private void Cancel()
        {
            // 清空所有输入数据
            TaskNumber = string.Empty;
            TaskName = string.Empty;
            StationId = string.Empty;
            TaskColor = "#1890FF";
            PlanQuantity = _planQuantity; // 恢复默认值
            PlanStartTime = _planStartTime;
            PlanEndTime = _planEndTime;
            Remarks = string.Empty;
            
            // 重置系统编号开关
            IsSystemNumber = true;
            
            DialogResult = false;
            Close();
        }

        private void Close()
        {
            // 关闭对话框的逻辑将在代码后台处理
        }

        private void PickColor()
        {
            // 简单的颜色选择器实现
            var colors = new[] { "#1890FF", "#52C41A", "#FA8C16", "#F5222D", "#722ED1", "#13C2C2", "#FAAD14", "#A0D911" };
            var random = new Random();
            TaskColor = colors[random.Next(colors.Length)];
        }
        #endregion

        #region 私有方法
        private void InitializeDefaultValues()
        {
            // 设置默认值，使用从排产页面获取的数据
            PlanQuantity = _planQuantity;
            PlanStartTime = _planStartTime;
            PlanEndTime = _planEndTime;
            TaskColor = "#1890FF";
            
            // 如果启用系统编号，生成任务编号
            if (IsSystemNumber)
            {
                GenerateSystemTaskNumber();
            }
        }

        private void GenerateSystemTaskNumber()
        {
            // 生成系统编号：年月日时分秒毫秒
            var now = DateTime.Now;
            TaskNumber = $"TASK{now:yyyyMMddHHmmssfff}";
        }

        private void LoadStationNames()
        {
            // 加载测试站点数据
            var testStations = new[]
            {
                new StationModel { Id = "ZD0801", Name = "站点一" },
                new StationModel { Id = "ZD0802", Name = "站点二" },
                new StationModel { Id = "ZD0803", Name = "站点三" },
                new StationModel { Id = "ZD0804", Name = "站点四" },
                new StationModel { Id = "ZD0805", Name = "站点五" }
            };

            foreach (var station in testStations)
            {
                StationNames.Add(station);
            }

            // 默认选择第一个站点
            if (StationNames.Count > 0)
            {
                SelectedStationName = StationNames[0];
            }
        }

        private bool ValidateInput()
        {
            if (string.IsNullOrWhiteSpace(TaskNumber))
            {
                MessageBox.Show("请输入任务编号", "验证失败", MessageBoxButton.OK, MessageBoxImage.Warning);
                return false;
            }

            if (string.IsNullOrWhiteSpace(TaskName))
            {
                MessageBox.Show("请输入任务名称", "验证失败", MessageBoxButton.OK, MessageBoxImage.Warning);
                return false;
            }

            if (SelectedStationName == null)
            {
                MessageBox.Show("请选择站点名称", "验证失败", MessageBoxButton.OK, MessageBoxImage.Warning);
                return false;
            }

            if (string.IsNullOrWhiteSpace(TaskColor))
            {
                MessageBox.Show("请选择任务颜色", "验证失败", MessageBoxButton.OK, MessageBoxImage.Warning);
                return false;
            }

            if (PlanQuantity <= 0)
            {
                MessageBox.Show("请输入有效的计划数量", "验证失败", MessageBoxButton.OK, MessageBoxImage.Warning);
                return false;
            }

            if (PlanStartTime >= PlanEndTime)
            {
                MessageBox.Show("开工时间必须早于完工时间", "验证失败", MessageBoxButton.OK, MessageBoxImage.Warning);
                return false;
            }

            return true;
        }
        #endregion

        #region INotifyPropertyChanged
        public event PropertyChangedEventHandler? PropertyChanged;
        protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
        #endregion
    }

    /// <summary>
    /// 站点模型
    /// </summary>
    public class StationModel
    {
        public string Id { get; set; } = string.Empty;
        public string Name { get; set; } = string.Empty;
    }
} 